const { Controller } = require("uni-cloud-router");
const AlipaySdk = require('alipay-sdk').default
const fs = require('fs');
const path = require('path');
module.exports = class UserController extends Controller {
  getPhoneByUniverify() {
		const { ctx, service } = this;
    return this.service.user.getPhoneByUniverify(ctx.data.access_token,ctx.data.openid);
  }
	clear() {
		return this.service.user.clear();
	}
	register(){
		const { ctx, service } = this;
		return this.service.user.register(ctx.data.username,ctx.data.password);
	}
	login(){
		const { ctx, service } = this;
		return this.service.user.login(ctx.data.username,ctx.data.password);
	}
	getUser(){
		const { ctx, service } = this;
		return this.service.user.getUser(ctx.data.username,ctx.data.password);
	}
	async loginByGitee(){
		const { ctx, service } = this;
		const code=ctx.event.queryStringParameters.code
		const client_id='435c7cbf41777a7710901a1c50022b3d2de5df21f4d13c6fab1e8e652eeacfa1'
		const redirect_uri='https://b33db069-91a2-42ff-a831-31fbd5a04b97.bspapp.com/shop-api/user/loginByGitee'
		const client_secret='4444aab983559b8a89c6e478e211a6bb7f30db80bbede5507917ae83a08c2c26'
		const url=`https://gitee.com/oauth/token?grant_type=authorization_code&code=${code}&client_id=${client_id}&redirect_uri=${redirect_uri}&client_secret=${client_secret}`
		uniCloud.logger.log(`gitee code: ${code}`)
		const res = await uniCloud.httpclient.request(url, {
			method: 'POST',
			data: {},
			contentType: 'json',
			dataType: 'json'
		})
		if(res.status==200){
			uniCloud.logger.log(`gitee access_token: ${res.data.access_token}`)
			const userUrl=`https://gitee.com/api/v5/user?access_token=${res.data.access_token}`
			uniCloud.logger.log(`gitee requset userInfo: ${userUrl}`)
			const res1 = await uniCloud.httpclient.request(userUrl, {
				method: 'GET',
				contentType: 'json',
				dataType: 'json'
			})
			if(res1.status==200){
				const user=res1.data
				return this.service.user.loginByGitee(user);
			}
		}
	}
	async loginByQQ(){
		const { ctx, service } = this;
		const code=ctx.event.queryStringParameters.code
		const client_id='101992679'
		const redirect_uri='https://b33db069-91a2-42ff-a831-31fbd5a04b97.bspapp.com/shop-api/user/loginByQQ'
		const client_secret='a758266e224ac16379d89d63f84c210c'
		const url=`https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=${client_id}&client_secret=${client_secret}&code=${code}&redirect_uri=${redirect_uri}&fmt=json`
		uniCloud.logger.log(`QQ code: ${code}`)
		uniCloud.logger.log(`QQ requset tokenUrl: ${url}`)
		const res = await uniCloud.httpclient.request(url, {
			method: 'GET',
			data: {},
			contentType: 'json',
			dataType: 'json'
		})
		if(res.status==200){
			uniCloud.logger.log(`QQ access_token: ${res.data.access_token}`)
			const openidUrl=`https://graph.qq.com/oauth2.0/me?access_token=${res.data.access_token}&fmt=json`
			uniCloud.logger.log(`QQ requset openidUrl: ${openidUrl}`)
			const res1 = await uniCloud.httpclient.request(openidUrl, {
				method: 'GET',
				contentType: 'json',
				dataType: 'json'
			})
			uniCloud.logger.log(`QQ openid: ${res1.data.openid}`)
			if(res1.status==200){
				const user=res1.data
				const userUrl=`https://graph.qq.com/user/get_user_info?access_token=${res.data.access_token}&oauth_consumer_key=${client_id}&openid=${res1.data.openid}`
				uniCloud.logger.log(`QQ requset userUrl: ${userUrl}`)
				const res2 = await uniCloud.httpclient.request(userUrl, {
					method: 'GET',
					contentType: 'json',
					dataType: 'json'
				})
				return this.service.user.loginByQQ(res1.data.openid,res2.data);
			}
		}
	}
	async loginByWX(){
		const { ctx, service } = this;
		const code=ctx.event.queryStringParameters.code
		const appid='wxc313be1e0d2d00e1'
		const redirect_uri='https://b33db069-91a2-42ff-a831-31fbd5a04b97.bspapp.com/shop-api/user/loginByWX'
		const app_secret='0248835914302a0581086fec8700ce44'
		const url=`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${app_secret}&code=${code}&grant_type=authorization_code`
		uniCloud.logger.log(`WX code: ${code}`)
		uniCloud.logger.log(`WX requset tokenUrl: ${url}`)
		const res = await uniCloud.httpclient.request(url, {
			method: 'GET',
			data: {},
			contentType: 'json',
			dataType: 'json'
		})
		if(res.status==200){
			uniCloud.logger.log(`WX access_token: ${res.data.access_token}`)
			const userUrl=`https://api.weixin.qq.com/sns/userinfo?access_token=${res.data.access_token}&openid=${res.data.openid}&lang=zh_CN`
			uniCloud.logger.log(`WX requset userUrl: ${userUrl}`)
			const res1 = await uniCloud.httpclient.request(userUrl, {
				method: 'GET',
				contentType: 'json',
				dataType: 'json'
			})
			if(res1.status==200){
				return this.service.user.loginByWX(res.data.openid,res1.data);
			}
		}
	}
	async loginByAliPay(){
		const { ctx, service } = this;
		//const code=ctx.event.queryStringParameters.app_auth_code
		const code=ctx.event.queryStringParameters.auth_code
		uniCloud.logger.log('AliPay Auth code: '+code)
		const privatePath=path.join(__dirname,'../alipay-private-key.pem')
		const publicPath=path.join(__dirname,'../alipay-public-key.pem')
		uniCloud.logger.log('privatePath: '+privatePath)
		uniCloud.logger.log('publicPath: '+publicPath)
		try{
			const alipaySdk = new AlipaySdk({
			  appId: '2016092000556038',
			  privateKey: fs.readFileSync(privatePath, 'ascii'),
				alipayPublicKey:fs.readFileSync(publicPath, 'ascii'),
				gateway:'https://openapi.alipaydev.com/gateway.do'
			});
			uniCloud.logger.log('AlipaySdk init')
			const res = await alipaySdk.exec('alipay.system.oauth.token', {
				grantType:'authorization_code',
				code:code
			});
			//uniCloud.logger.log(res)
			if(res.accessToken){
				const res1 = await alipaySdk.exec('alipay.user.info.share', {
					authToken:res.accessToken
				});
				//uniCloud.logger.log(res1)
				if(res1.code=='10000'){
					return this.service.user.loginByAliPay(res1)
				}
			}
		}catch(e){
			uniCloud.logger.log(e)
		}
	}
};